const {
	Service
} = require("uni-cloud-router");

let cheerio = require('cheerio'); //爬虫
let iconv = require('iconv-lite'); //处理gbk编码的网页
let Entities = require('html-entities').XmlEntities;
let entities = new Entities();

module.exports = class BookService extends Service {
	//解析规则
	// {
	//       "encode": "utf-8",
	//       "host": "http://www.xbiqugu.net",
	//       "newHost": "",
	//       "cataPath": "#list > dl > dd:nth-child(n+1) >a",
	//       "contentPath": "#content",
	//       "replaceStr": [
	//         "最新网址：www.xbiqugu.net",
	//         "手机站全新改版升级地址：http://wap.xbiqugu.net，数据和书签与电脑站同步，无广告清新阅读！",
	//         "亲,点击进去,给个好评呗,分数越高更新越快,据说给香书小说打满分的最后都找到了漂亮的老婆哦!",
	//         "手机站全新改版升级地址：https://wap.xbiquge.info，数据和书签与电脑站同步，无广告清新阅读！"
	//       ]
	//     }

	/**
	 * 新笔趣阁书籍搜索
	 **/
	async searchBqg() {

		var url = "http://www.xbiqugu.net/modules/article/waps.php";

		const res = await uniCloud.request({
			url: url,
			method: "POST",
			data: {
				"searchkey": this.ctx.data.searchKey
			},
			dataType: 'text'
		});

		var body = res.data;

		var $ = cheerio.load(body);

		var path = "#checkform > table > tbody > tr:nth-child(n+2)"
		var list = [];
		$(path).each((index, element) => {


			var book = {

			};
			$(element).find("td").each((i, e) => {
				if (i == 0) {
					$(e).find("a").each((ii, ee) => {

						book.link = $(ee).attr("href");
						book.title = $(ee).text();

					})

				}
				if (i == 2) {
					book.autor = $(e).text();
				}
				if (i == 4) {
					book.time = $(e).text();
				}
			})
			list.push(book)

		})
		return list;
	}

	/**
	 * 获取书籍章节目录
	 */
	async getBookCata() {
		var url = this.ctx.data.url;
		var encode = 'utf-8';
		var xpath = "#list > dl > dd:nth-child(n+1) >a";
		const res = await uniCloud.request({
			url: url,
			method: "GET",
			dataType: 'text'
		});

		var body = res.data;
		// console.log("body:" + body);

		var $ = cheerio.load(body)

		//兼容网页编码格式
		if (encode == 'utf-8') { //如果网页是utf-8的编码

		} else { //如果网页是gbk的编码
			body = iconv.decode(body, 'gbk'); //转换gbk编码的页面内容
			$ = cheerio.load(body);
		}

		var data = [];

		$(xpath).each((index, element) => {
			// console.log("index:" + index);
			var href = $(element).attr("href");
			var title = entities.decode($(element).text())
			data.push({
				title: title,
				url: href
			});
		})
		//这里可以自行根据需要加redis缓存
		// if (data.length > 0) {
		// 	///缓存3小时

		// 	await redis.set('bookCata:' + url, JSON.stringify(data), 'EX', 4 * 3600)
		// }

		//返回数据给客户端
		return data
	}



	async getBookContentWithOutCache() {
		var host = this.ctx.data.host;
		var url = this.ctx.data.url;
		/**
		 * 处理域名
		 */
		var http = host.split("//");
		host = http[0] + "//" + http[1].split("/")[0];


		var encode = 'utf-8';
		var xpath = "#content";
		var bookUrl = `${host}${url}`;
		//一些原来网页上的影响阅读的数据，可以设置未替换掉
		var replceArr = [
			"最新网址：www.xbiqugu.net",
			"手机站全新改版升级地址：http://wap.xbiqugu.net，数据和书签与电脑站同步，无广告清新阅读！",
			"亲,点击进去,给个好评呗,分数越高更新越快,据说给香书小说打满分的最后都找到了漂亮的老婆哦!",
			"手机站全新改版升级地址：https://wap.xbiquge.info，数据和书签与电脑站同步，无广告清新阅读！"
		]

		/**
		 * 请求内容数据
		 */
		const res = await uniCloud.httpclient.request(bookUrl, {
			method: 'GET',
			gzip: true,
			encoding: null,
			timeout: 9000,
			followRedirect: true
		})
		var body = res.data;
		var $ = cheerio.load(body)
		//兼容网页编码格式
		if (encode == 'utf-8') { //如果网页是utf-8的编码

		} else { //如果网页是gbk的编码
			body = iconv.decode(body, 'gbk'); //转换gbk编码的页面内容
			$ = cheerio.load(body);
		}


		var html = $(xpath).html();
		if (replceArr && replceArr.length > 0) {
			replceArr.forEach(a => {
				var find = a.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
				var reg = new RegExp(find, 'g')
				html = html.replace(reg, '');
				// html = html.replace(a, "")
			});
		}

		//可以使用redis缓存
		// if (html && html.length > 0) {
		// 	///缓存3小时
		// 	html = `<p style='word-wrap: break-word; table-layout: fixed; word-break: break-all'>${html}</p>`
		// 	await redis.set('bookContent:' + bookUrl, html, 'EX', 8 * 3600)
		// }


		//返回数据给客户端
		return html;
	}

	/*
	
	获取书籍章节内容
	*/
	async getBookContent() {
		var host = this.ctx.data.host;
		var url = this.ctx.data.url;
		var http = host.split("//");
		host = http[0] + "//" + http[1].split("/")[0];

		var encode = 'utf-8';
		var xpath = "#content";
		var bookUrl = `${host}${url}`;
		//一些原来网页上的影响阅读的数据，可以设置未替换掉
		var replceArr = [
			"最新网址：www.xbiqugu.net",
			"手机站全新改版升级地址：http://wap.xbiqugu.net，数据和书签与电脑站同步，无广告清新阅读！",
			"亲,点击进去,给个好评呗,分数越高更新越快,据说给香书小说打满分的最后都找到了漂亮的老婆哦!",
			"手机站全新改版升级地址：https://wap.xbiquge.info，数据和书签与电脑站同步，无广告清新阅读！"
		]


		const res = await uniCloud.request({
			url: bookUrl,
			method: "GET",
			dataType: 'text'
		});

		console.log("bookurl:" + bookUrl);
		var body = res.data;
		var $ = cheerio.load(body)
		//兼容网页编码格式
		if (encode == 'utf-8') { //如果网页是utf-8的编码

		} else { //如果网页是gbk的编码
			body = iconv.decode(body, 'gbk'); //转换gbk编码的页面内容
			$ = cheerio.load(body);
		}
		var html = $(xpath).html();
		if (replceArr && replceArr.length > 0) {
			replceArr.forEach(a => {
				// html = html.replace(a, "")
				var find = a.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
				var reg = new RegExp(find, 'g')
				html = html.replace(reg, '');
			});
		}

		// if (html && html.length > 0) {
		// 	///缓存3小时

		// 	//
		// 	html = `<p style='word-wrap: break-word; table-layout: fixed; word-break: break-all'>${html}</p>`
		// 	await redis.set('bookContent:' + bookUrl, html, 'EX', 8 * 3600)
		// }


		//返回数据给客户端
		return html
	}






	async insertBookError() {
		const db = uniCloud.database();
		let id = await db.collection('BookError').add(this.ctx.data);

		if (id) return new {
			errCode: 0,
			errMsg: "已经上报，我们会尽快处理，谢谢您提供的信息！"
		};

		return new {
			errCode: 2001,
			errMsg: "上报错误"
		}
	}



};
/**
 * [通过参数名获取url中的参数值]
 * 示例URL:"http://test/getIndex/indexRequest.html?uid=admin&passWord=123456&fid=1314&name=阿豪";
 * @param  {[string]} queryName [参数名]
 * @return {[string]}           [参数值]
 */
function GetQueryValue(url, queryName) {
	// debugger;
	var reg = new RegExp("(^|&)" + queryName + "=([^&]*)(&|$)", "i");
	// 获取url中"?"符后的字符串并正则匹配
	var r = url.substr(1).match(reg);
	if (r != null) {
		return decodeURI(r[2]);
	} else {
		return null;
	}
}